//
//  BmpViewController.m
//  Ikinloop-demo
//
//  Created by Li Shen on 2021/5/28.
//  Copyright © 2021 lyh. All rights reserved.
//

#import "EcgImageViewController.h"
#import "IKPublicUtil.h"
#import <IKLibrary/IKLibrary.h>
//#import "ECGImageView.h"
//#import "ECGUserInfo.h"

@interface EcgImageViewController ()<UIScrollViewDelegate>

@property (nonatomic, strong) UIImageView *imageView;
@property (nonatomic, assign) NSInteger dataLength;
@property (nonatomic, strong) UIImage *savedImage;
@property (nonatomic, strong) NSDictionary *smartResultDic;

@end

@implementation EcgImageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"图片";
    self.view.backgroundColor = [UIColor whiteColor];
//    self.edgesForExtendedLayout = UIRectEdgeAll;
//    self.automaticallyAdjustsScrollViewInsets = YES;
    [self loadECGData];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"分享" style:UIBarButtonItemStylePlain target:self action:@selector(shareImage)];
    
    UIButton *saveBtn = [[UIButton alloc] initWithFrame:CGRectMake(10, 20, 150, 40)];
    saveBtn.backgroundColor = ECG_COLOR_BACKGROUND;
    [saveBtn setTitle:@"保存到相册" forState:UIControlStateNormal];
    [saveBtn setTitleColor:COLOR_BLACK_6F6F6F forState:UIControlStateNormal];
//    [saveBtn addTarget:self action:@selector(saveImageToPhotos) forControlEvents:UIControlEventTouchUpInside];
    [saveBtn addTarget:self action:@selector(shareImage) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:saveBtn];
    
}

#pragma mark - 加载页面图标数据
- (void)loadECGData{
    if([IKPublicUtil isEmpty:self.tarFilePath] || ![self.tarFilePath.pathExtension isEqualToString:@"tar"]){
        NSLog(@"传入的tar包路径不对");
        return;
    }
    NSLog(@"tarFilePath--%@",self.tarFilePath);
    [self setupView];
}

- (void)shareImage{
    if(self.savedImage == nil){
        return;
    }
    //分享的标题
    NSString *textToShare = @"心电报告";
    //分享的图片
    UIImage *imageToShare = self.savedImage;

    NSArray *activityItems = @[textToShare,imageToShare];
        
    UIActivityViewController *activityVC = [[UIActivityViewController alloc]initWithActivityItems:activityItems applicationActivities:nil];

//    activityVC.excludedActivityTypes = @[UIActivityTypePrint, UIActivityTypeCopyToPasteboard,UIActivityTypeAssignToContact,UIActivityTypeSaveToCameraRoll];
        
    [self presentViewController:activityVC animated:YES completion:nil];
        
    //分享之后的回调
    activityVC.completionWithItemsHandler = ^(UIActivityType  _Nullable activityType, BOOL completed, NSArray * _Nullable returnedItems, NSError * _Nullable activityError) {
        if (completed) {
            NSLog(@"completed");
            //分享 成功
        } else  {
            NSLog(@"cancled");
            //分享 取消
        }
    };
}

//实现该方法
- (void)saveImageToPhotos
{
    if(self.savedImage == nil){
        return;
    }
    UIImageWriteToSavedPhotosAlbum(self.savedImage, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
    //因为需要知道该操作的完成情况，即保存成功与否，所以此处需要一个回调方法image:didFinishSavingWithError:contextInfo:
}

//回调方法
- (void)image: (UIImage *) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo
{
    NSString *msg = nil ;
    if(error != NULL){
        msg = @"保存图片失败" ;
    }else{
        msg = @"保存图片成功" ;
    }
    NSLog(@"msg---%@",msg);
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:msg preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [self presentViewController:alertController animated:true completion:nil];

}

- (void)setTarFilePath:(NSString *)tarFilePath{
    _tarFilePath = tarFilePath;
}

-(NSString*)getCurrentTimes{

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    NSDate *datenow = [NSDate date];
    NSString *currentTimeString = [formatter stringFromDate:datenow];
    return currentTimeString;
}

- (void)setupView{
    
    CGFloat width = [UIScreen mainScreen].bounds.size.width;
    CGFloat height = [UIScreen mainScreen].bounds.size.height;
//    CGFloat height = self.view.frame.size.height;

    UIScrollView *bgScrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
    bgScrollView.contentSize = CGSizeMake(width, height);
    bgScrollView.delegate = self;

    //1.ECGImageView的宽度默认为手机屏幕的宽度
    ECGImageView *ecgImagView  = [[ECGImageView alloc] init];

    //2.设置个人基本信息，选填，没有的话，不显示基本信息。
//    NSString *userInfo = [self createEcgUserInfo];
//    [ecgImagView setUserInfo:userInfo];
    //3.设置检测设备序列号，没传则不显示
    [ecgImagView setDeviceId:@"18231301223"];
    //4.设置检测时间
    [ecgImagView setDetectTime:[self getCurrentTimes]];
    //5.设置检测时长，一般为40秒
    [ecgImagView setDuration:@"40"];
//    NSString *result = @"{\"ecgval\": {         \"hrmean\": \"70\",          \"breath\": \"9\",          \"pbcnt\": \"0\",          \"hrmax\": \"72\",          \"suspectedflag\": false,          \"heartage\": \"36\",          \"pressure\": \"81\",          \"hrv\": \"12\",          \"hrmin\": \"68\"     },      \"ecgsymps\": [         {             \"sympcode\": \"0.0\",              \"name\": \"未见异常\",              \"suggestion\": \"本次测试心电图波形规律,未见异常。建议您：保持养成良好生活习惯，多吃绿色蔬菜、水果，定期运动、定时排便，避免熬夜。\"         },          {             \"sympcode\": \"0.003\",              \"name\": \"焦虑\",              \"suggestion\": \"您的心理状态偏向焦虑，可能引起的原因：工作生活压力、频繁应酬、加班熬夜。长期以往会对生理和心理上都会产生不同程度的损害，会影响免疫系统，易于患病。建议改善习惯、保持心情放松、适度运动、多做深呼吸。\"         },          {             \"sympcode\": \"I48\",              \"name\": \"呼吸过慢\",              \"suggestion\": \"呼吸过慢常见于运动员、长期运动的人，由于经常锻炼肺活量比一般人大，每次吸入的氧气量大所需的时间稍多，因此频率降低，如没有合并不适症状，一般属于正常现象，如果是复杂病情引起的过缓应及时就诊。\"         }     ] }";

//    [ecgImagView setEcgSmartResult:result];
    //6.设置心电检测结果JSON字符串，这个结果就是心电检测结束后返回的字符串
    [ecgImagView setEcgSmartResult:self.ecgSmartResult];

    //7.传入tar包路径
    [ecgImagView setEcgDataFilePath:self.tarFilePath];
    //8.执行画的动作
    [ecgImagView drawEcgReport];
    UIImage *image = [ecgImagView getEcgImage];
    self.savedImage = image;
    NSLog(@"size::%@",NSStringFromCGSize(image.size));
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, image.size.width, image.size.height)];
    imageView.image = image;
    imageView.contentMode = UIViewContentModeTop;
    
    [imageView setMultipleTouchEnabled:YES];
    [imageView setUserInteractionEnabled:YES];
    self.imageView = imageView;
    
    [bgScrollView setMinimumZoomScale:1];
    [bgScrollView setMaximumZoomScale:3];
    [bgScrollView setScrollEnabled:true];
    
    [bgScrollView addSubview:imageView];
    [self.view addSubview:bgScrollView];
    [bgScrollView setZoomScale:1];
}

-(NSString *)createEcgUserInfo
{
    //todo 以下代码为模拟读取用户信息代码。客户可对此代码进行删除修改。
    //todo 如可以从自己的后台系统读取用户数据。
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[@"ssname"] = @"竹小信"; //名字必须有,否则传入无效
    dic[@"gender"] = @"10000"; //10000 男 20000 女
    dic[@"age"] = @"33";
    dic[@"weight"] = @"66";
    dic[@"height"] = @"177";
    NSError *err = nil;
    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dic options:0 error:&err];
    NSString * userInfo = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    return userInfo;
}

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
    return self.imageView;
}

//    [ecgImagView setHeadFontSize:[UIFont systemFontOfSize:24]];
//    [ecgImagView setHeadFontColor:[UIColor redColor]];
//    [ecgImagView setTitleFontSize:[UIFont systemFontOfSize:16]];
//    [ecgImagView setTitleFontColor:[UIColor blueColor]];
//    [ecgImagView setContentFontSize: [UIFont systemFontOfSize:16]];
//    [ecgImagView setContentFontColor:[UIColor brownColor]];
//
//    [ecgImagView setWaveLineColor:[UIColor blueColor]];
//    [ecgImagView setGridLineColor:[UIColor redColor]];
@end
